const Koa = require('koa')
const session = require('koa-session');
const { koaBody } = require('koa-body');
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const index = require('./routes/index')
const users = require('./routes/users')
const cors = require('koa2-cors');
const compress = require('koa-compress');

// error handler
onerror(app)



const CONFIG = {
  key: 'koa.sess',
  maxAge: 86400000,
  autoCommit: true,    /** (boolean) automatically commit headers (default true) */
  overwrite: true,     /** (boolean) can overwrite or not (default true) */
  // httpOnly: true,   /** (boolean) httpOnly or not (default true) */
  signed: true,        /** (boolean) signed or not (default true) */
  rolling: true,       /** 每次请求重新设置时间*/
  renew: false,        /** 请求时在快要过期时重新设置cookie*/
  sameSite: null,      /** (string) session cookie sameSite options (default null, don't set it) */
};
app.keys = ['some secret hurr'];
app.use(session(CONFIG, app));

// 使用 koa-body 中间件解析请求体
app.use(koaBody({ multipart: true }));
app.use(cors({ credentials: true }));
// middlewares
app.use(compress({
  filter(content_type) {
    return /text/i.test(content_type)
  },
  threshold: 2048,
  gzip: {
    flush: require('zlib').constants.Z_SYNC_FLUSH
  },
  deflate: {
    flush: require('zlib').constants.Z_SYNC_FLUSH,
  },
  br: false // disable brotli
}))
app.use(cors());
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
